package com.fita.scheduler.handler.impl;

import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.http.annotation.Rao;
import com.fita.scheduler.handler.ExchangeRateHandler;
import com.fita.scheduler.rao.ExchangeRateRao;
import org.apache.commons.collections.ListUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.fluent.Request;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;

/**
 * @description:
 * @author: 11200
 * @date: 2019/8/1
 */
@Component("exchangeRateHandler")
public class ExchangeRateHandlerImpl implements ExchangeRateHandler {

    @Value("#{ctx['exchange-rate.sina.url']}")
    private String fetchExchangeRateUrl;

    @Rao
    private ExchangeRateRao exchangeRateRao;

    private static final int partLength = "var hq_str_h_".length();

    private final static Logger logger = LoggerFactory.getLogger(ExchangeRateHandlerImpl.class);

    /**
     * 获取最新汇率
     * http://hq.sinajs.cn/?list=h_RMBUSD,h_RMBUSD
     * @param froms
     * @param to
     * @return
     */
    public List<Map<String, String>> fetchNewExchangeRate(List<String> froms, String to){

        List<Map<String, String>> results = new ArrayList<>();

        List<String> params = new ArrayList<>();

        froms.stream().forEach(form -> {
            form = form.trim();
            String var = "h_" + to + form;
            params.add(var);
        });

        String queryValue = StringUtils.join(params, ",");

        //HttpResult httpResult = exchangeRateRao.fetchExchangeRate(fetchExchangeRateUrl, queryValue);

        HttpResponse httpResponse = null;
        try {
            httpResponse = Request.Get(fetchExchangeRateUrl + "?list=" + queryValue).execute().returnResponse();

            String responseText = EntityUtils.toString(httpResponse.getEntity());

            String[] strings = responseText.split(";");

            Arrays.stream(strings).forEach(s -> {
                if (!s.contains("=")){
                    return;
                }
                String[] split = s.split("=");
                String key = split[0].substring(partLength + to.length() + 1);
                if (!split[1].contains(",")){
                    return;
                }
                String value = split[1].split(",")[1];
                Map<String, String> tmp = new HashMap<>();
                tmp.put(key, value);
                results.add(tmp);
            });
            return results;

        } catch (IOException e) {

            logger.error("#fetchNewExchangeRate() call remote api error [{}]", e);

            return Collections.emptyList();
        }


    }
}
